<template>
    <div class="whiteCard">
        <addPlan @add='handleAdd' @batchImport='batchImport' ref="addPlan" :seeFlag="see" planTag="IF"
                 :term-dis="false"></addPlan>
        <goodTable style="margin-top:20px" :Tag="tag" ref="goodTable" @edit="edit" @goodList="goodList" :goods="true"
                   :seeFlag="see"></goodTable>
        <div class="btn">
            <el-button type="primary" :loading="loading"
                       @click="add" v-if="!see">生成计划
            </el-button>
        </div>
        <el-dialog title=""
                   :visible.sync="dialogVisible"
                   width="65%"
                   :before-close="handleClose">
            <addGoods v-if="dialogVisible" :showGoods="false" ref="addGoods" :seeFlag="see"></addGoods>
            <newLeftMenu2 ref="newLeftMenu2" v-show="false"></newLeftMenu2>
            <span slot="footer"
                  class="dialog-footer">
        <el-button @click="save">保存</el-button>
        <el-button type="primary"
                   @click="dialogVisible = false">取消</el-button>
      </span>
        </el-dialog>
        <el-dialog title=""
                   :visible.sync="dialogVisible1"
                   width="65%"
                   :before-close="handleClose1">
            <addGoods1 v-if="dialogVisible1" ref="addGoods1" @addItem="addItem" :seeFlag="see"></addGoods1>
        </el-dialog>
    </div>
</template>

<script>
import addPlan from './module/addPlan.vue'
import goodTable from './module/goodTable.vue'
import addGoods from './module/addGoods.vue'
import addGoods1 from './module/addGoods1.vue'
import newLeftMenu2 from '@/components/newLeftMenu2.vue'
import * as XLSX from 'xlsx'
import {isStringEmpty} from '@/util/StringUtil' // 导入工具函数
export default {
    name: 'whiteCard',
    components: {addPlan, goodTable, addGoods, addGoods1, newLeftMenu2},
    data() {
        return {
            dialogVisible: false,
            dialogVisible1: false,
            tag: '',
            index: -1,
            see: false,
            loading: false,
            oldFormJson: '',
            dataList: {}
        }
    },
//通过路由规则，离开该组件时被调用
    beforeRouteLeave(to, from, next) {
        // console.log('About--beforeRouteLeave',to,from)
        let nowJsonData = JSON.stringify(this.$refs.addPlan.form)
        let oldFormJson = JSON.stringify(this.$refs.addPlan.oriForm)
        if (nowJsonData != oldFormJson && to.query.name != 'boxGoods') {
            this.$nextTick(() => {
                this.$confirm('存在未提交信息，确认关闭？', {
                    closeOnHashChange: false,
                    closeOnClickModal: false,
                    distinguishCancelAndClose: true,
                    closeOnPressEscape: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                })
                    .then(_ => {
                        this.$store.commit('setActiveMenuPath', next.fullPath)
                        next()
                    })
                    .catch(_ => {
                        this.$store.commit('setActiveMenuPath', from.fullPath)
                        this.$nextTick(() => {
                            this.$refs.newLeftMenu2.getPath(from.fullPath)
                            this.$refs.newLeftMenu2.linkTab(from.fullPath)
                        })
                    });
            })
        } else {
            next()
        }
    },
    methods: {
        handleAdd() {
            this.dialogVisible = true
            this.$nextTick(() => {
                // 存旧数据
                this.oldFormJson = this.$refs.addGoods.getNowData()
            })
        },
        addItem(item) {
            this.$set(this.$refs.goodTable.tableData[this.index], 'containerGoodList', item)
            this.dialogVisible1 = false
        },
        handleClose(done) {
            let nowJsonData = this.$refs.addGoods.getNowData()
            if (this.oldFormJson == nowJsonData) {
                this.dialogVisible = false
            } else {
                this.$confirm('存在未提交信息，确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            }
        },
        handleClose1() {
            this.dialogVisible1 = false
        },
        goodList(goods, index) {
            this.dialogVisible1 = true
            this.$nextTick(() => {
                if (undefined !== goods.containerGoodList)
                    this.$refs.addGoods1.goods = goods.containerGoodList
                this.index = index
            })
        },
        save() {
            this.$refs.addGoods.$refs.form.validate((valid) => {
                if (valid) {
                    this.save1()
                } else {
                    return false
                }
            });
        },
        save1() {
            let c = JSON.parse(JSON.stringify(this.$refs.addGoods.form))
            if (undefined !== c.index) {
                this.$set(this.$refs.goodTable.tableData, c.index, c)
                this.$refs.goodTable.myUpdate()
            } else {
                this.$refs.goodTable.tableData.push(c)
            }
            this.$refs.addGoods.form = {}
            this.dialogVisible = false
        },

        initDictData() {
            this.dataList = {
                cstCoperMap: {}, //cus 持箱人
                INTERNALFG_MAP: {}, //INTERNALFG_IM 贸易类型
                portsMap: {},
                boxMap: [], //boxSize 箱型
                hzMap: {},
                hdMap: {}
            }
            // 持箱人
            this.$api.getCustomerRelations({})
                .then((res) => {
                    this.dataList.cstCoperMap = new Map(res.data.map(obj => [obj.relationTenantName, obj.relationTenantId]))
                }).catch()
            // 贸易类型
            this.$api.refCode({domain: 'INTERNALFG_IM',})
                .then((res) => {
                    this.dataList.INTERNALFG_MAP = new Map(res.data.data.map(obj => [obj.meaning, obj.lowValue]));
                }).catch()
            // 港口
            this.$api.port().then((res) => {
                this.dataList.portsMap = new Map(res.data.data.map(obj => [obj.portlocnnm, obj.portcd]));
            }).catch()
            // 货主
            this.$api.customerByType({tenantTypeName: '货主',})
                .then((res) => {
                    this.dataList.hzMap = new Map(res.data.data.map(obj => [obj.name, obj.customerCode]));
                }).catch()
            this.$api.customerByType({tenantTypeName: '货代',})
                .then((res) => {
                    this.dataList.hdMap = new Map(res.data.data.map(obj => [obj.containerType + obj.containerSize, obj.isoCode]));
                }).catch()
            // 箱型
            this.$api.containerTypeSizeInfo()
                .then((res) => {
                    this.dataList.boxMap = new Map(res.data.data.map(obj => [obj.containerType + obj.containerSize, obj.isoCode]));
                }).catch()
        },

        batchImport(file) {
            // console.log(this.dataList)
            const isExcel = /\.(xlsx|xls|csv)$/.test(file.name)
            if (!isExcel) {
                this.$message.error('只能上传 .xlsx、.xls、.csv 文件!')
                return false
            }

            // 创建一个文件读取器
            const reader = new FileReader();
            reader.onload = (e) => {
                // 1、拿取到json数组
                const data = new Uint8Array(e.target.result)
                const workbook = XLSX.read(data, {type: 'array'})
                const firstSheetName = workbook.SheetNames[0]
                const worksheet = workbook.Sheets[firstSheetName]
                const jsonArray = XLSX.utils.sheet_to_json(worksheet, {header: 1})
                if (jsonArray.length < 2) {
                    this.$message.error('无数据导入')
                    return false
                }

                // 简单空校验  并合并一箱多货  key为箱号 value 为 货数组
                const jsonMap = new Map();
                for (let i = 1; i < jsonArray.length; i++) {
                    let itemBox = jsonArray[i]
                    // 0-10 必填项不允许为空
                    if (isStringEmpty(itemBox[0])
                        || isStringEmpty(itemBox[1]) || isStringEmpty(itemBox[2])
                        || isStringEmpty(itemBox[3]) || isStringEmpty(itemBox[4])
                        || isStringEmpty(itemBox[5]) || isStringEmpty(itemBox[6])
                        || isStringEmpty(itemBox[7]) || isStringEmpty(itemBox[8])
                        || isStringEmpty(itemBox[9]) || isStringEmpty(itemBox[10])) {
                        this.$message.error('A-K列存在必填项为空,请检查')
                        return false
                    }

                    if (!isStringEmpty(itemBox[1]) && this.dataList.cstCoperMap.get(itemBox[1]) == null) {
                        this.$message.error(itemBox[1] + '持箱人不存在!')
                        return false
                    }

                    if (!isStringEmpty(itemBox[2]) && this.dataList.INTERNALFG_MAP.get(itemBox[2]) == null) {
                        this.$message.error('贸易类型填写错误!')
                        return false
                    }

                    if (!isStringEmpty(itemBox[6]) && this.dataList.boxMap.get(itemBox[6] + itemBox[7]) == null) {
                        this.$message.error(itemBox[6] + itemBox[7] + '箱型尺寸填写错误!')
                        return false
                    }

                    if (!isStringEmpty(itemBox[3]) && this.dataList.portsMap.get(itemBox[3]) == null) {
                        this.$message.error(itemBox[3] + '不存在!')
                        return false
                    }

                    if (!isStringEmpty(itemBox[4]) && this.dataList.portsMap.get(itemBox[4]) == null) {
                        this.$message.error(itemBox[4] + '不存在!')
                        return false
                    }

                    if (!isStringEmpty(itemBox[5]) && this.dataList.portsMap.get(itemBox[5]) == null) {
                        this.$message.error(itemBox[5] + '不存在!')
                        return false
                    }

                    if (!isStringEmpty(itemBox[11]) && this.dataList.hzMap.get(itemBox[11]) == null) {
                        this.$message.error(itemBox[11] + '货主不存在!')
                        return false
                    }

                    if (!isStringEmpty(itemBox[15]) && this.dataList.hdMap.get(itemBox[15]) == null) {
                        this.$message.error(itemBox[15] + '货代不存在!')
                        return false
                    }

                    const key = itemBox[0];
                    // 如果key已存在，则使用数组存储所有对应的value 10 - 15 为货
                    let goodsJson =
                        {
                            "planGoods": {
                                "billno": itemBox[10], // 提单号
                                "consignee": this.dataList.hzMap.get(itemBox[11]),
                                "consigneeName": itemBox[11], // 货主
                                "gname": itemBox[12], // 货名
                                "shipper": itemBox[13], // 发货人
                                "receiver": itemBox[14], // 收货人
                                "gagent": this.dataList.hdMap.get(itemBox[15]),
                                "gagentName": itemBox[15], // 货代
                                "tempUnit": '' // 温度单位
                            }
                        }
                    if (jsonMap.has(key)) {
                        jsonMap.get(key).push(goodsJson);
                    } else {
                        jsonMap.set(key, [goodsJson]);
                    }
                }

                // 列表清空
                this.$refs.goodTable.tableData = []
                this.$refs.goodTable.myUpdate()

                // 记录箱号遍历标志
                let traversedSet = new Set();
                for (let i = 1; i < jsonArray.length; i++) {
                    let itemBox = jsonArray[i]
                    if (traversedSet.has(itemBox[0])) {
                        continue;
                    }
                    traversedSet.add(itemBox[0])
                    let boxJson = {
                        "attachOperation": "WG",
                        "attachOperationName": "外港",
                        "containerGoodList": jsonMap.get(itemBox[0]),
                        "data": "",
                        "cntrno": itemBox[0], // 箱号
                        "cstCopercd": this.dataList.cstCoperMap.get(itemBox[1]),
                        "cstCopercdName": itemBox[1], // 持箱人
                        "internalfg": this.dataList.INTERNALFG_MAP.get(itemBox[2]), // 贸易类型
                        "internalfgName": itemBox[2], // 贸易类型
                        "potLdport": this.dataList.portsMap.get(itemBox[3]),  // 装货港
                        "potLdportName": itemBox[3],  // 装货港
                        "potUnldport": this.dataList.portsMap.get(itemBox[4]), // 卸货港
                        "potUnldportName": itemBox[4], // 卸货港
                        "potDstnport": this.dataList.portsMap.get(itemBox[5]), // 目的港
                        "potDstnportName": itemBox[5], // 目的港
                        "typeSize": [
                            itemBox[6], // 箱型
                            itemBox[7] // 箱尺寸
                        ],
                        "ctypecd": itemBox[6], // 箱型
                        "cszCsizecd": itemBox[7], // 箱尺寸
                        "isocd": this.dataList.boxMap.get(itemBox[6] + itemBox[7]),
                        "cweight": itemBox[8], // 箱货总重（吨）
                        "sealno": itemBox[9] // 铅封号
                    }
                    this.$refs.goodTable.tableData.push(boxJson)
                }
                this.$refs.goodTable.myUpdate()
            };
            reader.readAsArrayBuffer(file);
            // 如果需要继续上传文件，返回 true
            return false;
        },

        edit(e, e1, index) {
            this.dialogVisible = true
            this.$nextTick(res => {
                // console.log(e)
                // console.log(e1)
                // console.log(index)
                e.index = index
                this.$refs.addGoods.form = e
                this.$refs.addGoods.form1 = e1
                // 存旧数据
                this.oldFormJson = JSON.stringify(e)
            })
        },
        link() {
            this.$router.push({
                query: {
                    name: 'boxGoods'
                },
                name: 'success'
            })
        },
        getInfo() {
            this.$nextTick(() => {
                if (undefined !== this.$route.query.id) {
                    if ('see' === this.$route.query.state) {
                        this.see = true
                    } else {
                        this.see = false
                    }
                    this.$api.contentSelectAll({
                        id: this.$route.query.id
                    }).then(res => {
                        let data = res.data.data[0]
                        let name = this.$refs.addPlan.form.cstCoperName
                        this.$refs.addPlan.form = JSON.parse(JSON.stringify(data))
                        this.$refs.addPlan.form.cstCoperName = name
                        this.$refs.addPlan.$refs.myUpload.file = JSON.parse(JSON.stringify(data.planAttachmentList))
                        this.$refs.goodTable.tableData = JSON.parse(JSON.stringify(data)).planContainers
                    }).catch()
                }
            })
        },
        set(val) {
            // console.log(val)
            this.$refs.addPlan.set(val)
        },
        checkPlan() {
            let result = false
            this.$refs.addPlan.$refs.form.validate((valid) => {
                result = valid
            });
            return result
        },
        add() {
            this.loading = true
            let that = this
            let formPlan = this.checkPlan()
            if (!(formPlan)) {
                this.loading = false
                return
            }
            if (0 === this.$refs.goodTable.selection.length) {
                this.$message.error('请选择箱！')
                this.loading = false
                return
            }
            // console.log(this.$refs.goodTable.selection.length)
            let state = false
            this.$refs.goodTable.selection.forEach((element, index) => {
                if (undefined === element.containerGoodList || null === element.containerGoodList || 0 === element.containerGoodList.length) {
                    this.$message.error('勾选的第' + (index + 1) + '个箱子缺少货物信息！')
                    state = true
                    this.loading = false
                    return
                }
            });
            if (state) {
                return
            }
            let planContainers = JSON.parse(JSON.stringify(this.$refs.goodTable.selection))
            let form = JSON.parse(JSON.stringify(this.$refs.addPlan.form))
            form.planContainers = planContainers
            let par = ''
            if (undefined === form.id || null === form.id) {
                par = 'JZ_Add'
            } else {
                par = 'JZ_Edit'
            }
            this.$api.shipE(form, par).then(res => {
                if (200 === res.code) {
                    this.$message.success({
                        message: undefined !== form.id ? '编辑成功!' : '新增成功!', onClose() {
                            that.link()
                        }
                    })
                } else {
                    this.loading = false
                }
            }).catch(res => {
                this.loading = false
            })
        }
    },

    computed: {},

    mounted() {
        this.tag = 'PF'
        this.getInfo()
        this.initDictData()
    },
}
</script>
<style lang='less' scoped>
/deep/ .el-input.is-disabled .el-input__inner {
  color: #666

}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  color: #666
}

.whiteCard {
  background-color: #fff;
  padding: 15px 30px 40px 30px;
}

/deep/ .el-dialog__footer {
  text-align: center;

  .el-button {
    color: #fff;
    background: #0f47b8;
    height: 30px;
    width: 100px;
    padding: 5px 10px;
  }
}

/deep/ .el-dialog__header {
  padding: 0;
}

/deep/ .el-dialog__body {
  padding: 20px;
}

.btn {
  text-align: center;
  margin-top: 20px;

  .el-button {
    background: #0f47b8;
    height: 30px;
    padding: 5px 10px;
  }
}
</style>